package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());
        return menus;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> entities) {
        List<CategoryEntity> children = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查菜单是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 找到级联完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return (Long[]) paths.toArray(new Long[paths.size()]);
    }

    /**
     * @Cacheable  springcache，代表当前方法结果需要缓存，缓存中若没有则调用方法
     * 自定义：
     * 1.指定缓存key
     * 2.指定存活时间，application.properties中设置spring.cache.redis.time-to-live
     * 3.将数据保存为json格式，自定义配置类MyRedisCacheConfiguration
     *
     * @Cacheable有sync属性，设置为true，则调用加锁方法
     * 常规数据，读多写少，一致性要求不高，使用spring-cache，写模式只要设置了存活时间就够了
     * @return
     */
    @Override
    @Cacheable(value={"category"},key="'level1Categorys'")
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("----------执行了getLevel1Categorys-------------");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
    }

    @Override
    @Cacheable(value="category",key="#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("----------执行了getCatalogJson----------");
        return getCatalogJsonFromDb();
    }

    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        return getCatalogJsonFromRedisson();
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromRedis() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            Map<String, List<Catelog2Vo>> cats = getCatalogJsonFromDb();
            redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(cats));
            return cats;
        }
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromRedisson() {
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> data;
        try{
            data=getCatalogJsonFromDb();
        }finally {
            lock.unlock();
        }
        return data;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        //查出所有分类
        List<CategoryEntity> cats = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(cats, 0L);
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(cats, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //查询三级分类
                    List<CategoryEntity> level3s = getParent_cid(cats, l2.getCatId());
                    if (level3s != null) {
                        List<Catelog2Vo.Catelog3Vo> l3s = level3s.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo1 = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo1;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(l3s);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> cats, Long parentCid) {
        return cats.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
    }
}
